package com.kermel.andromeda.activities.alarm.add;

import java.util.Calendar;

import android.app.Activity;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;

import com.kermel.andromeda.R;
import com.kermel.andromeda.common.util.BundleUtil;
import com.kermel.andromeda.data.Alarm;
import com.kermel.andromeda.data.AlarmManager;
import com.kermel.andromeda.data.AlarmTimeModel;
import com.kermel.andromeda.data.settings.ClockSettings;
import com.kermel.andromeda.data.settings.SettingsManager;
import com.kermel.common.android.TextViewUtils;
import com.kermel.common.util.DateTimeUtils;
import com.kermel.common.util.RingtoneUtils;
import com.kermel.common.util.StringUtils;

public class AddAlarmActivity extends Activity {
    public static final int RESULT_ALARM_ADDED = 1;
    public static final int RESULT_ALARM_EDITED = 2;
    
    private Alarm alarm;
    
    private AlarmTimeModel alarmTimeModel;
    
    private TextView chooseAlarmSoundDisplay;
    private TextView chooseAlarmTimeDisplay;
    private CheckBox enabledInput;
    private CheckBox vibrateInput;
    private EditText nameInput;
    private Button doneButton;
    
    public AddAlarmActivity() {
        alarm = new Alarm();
    }
    
    public AddAlarmActivity(Alarm alarm) {
        this.alarm = alarm;
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     
        setContentView(R.layout.edit_alarm);
        
        storeWidgetHandles();
        
        attemptToRetrieveAlarmFromBundle(savedInstanceState);
        
        updateWidgetsWithValuesFromAlarm();
        
        initModels();
        
        initOnClickListeners();
    }
    
    private void storeWidgetHandles() {
        chooseAlarmTimeDisplay = (TextView)findViewById(R.id.editAlarmTimeDisplay);
        chooseAlarmSoundDisplay = (TextView)findViewById(R.id.editAlarmSoundDisplay);
        enabledInput = (CheckBox)findViewById(R.id.editAlarmEnabledInput);
        vibrateInput = (CheckBox)findViewById(R.id.editAlarmVibrateInput);
        nameInput = (EditText)findViewById(R.id.editAlarmNameInput);
        doneButton = (Button)findViewById(R.id.editAlarmDoneButton);
    }
    
    private void attemptToRetrieveAlarmFromBundle(Bundle savedInstanceState) {
        Alarm incomingAlarm = BundleUtil.retrieveAlarmFromBundleData(savedInstanceState, getIntent());
        
        if (incomingAlarm != null)
            alarm = incomingAlarm;
    }
    
    private void updateWidgetsWithValuesFromAlarm() {
        if (StringUtils.isBlank(alarm.name))
            alarm.name = getString(R.string.alarm);
        
        updateAlarmSoundDisplayText(alarm.ringtoneTitle);
        
        enabledInput.setChecked(alarm.enabled);
        nameInput.setText(alarm.name);
        chooseAlarmTimeDisplay.setText(Alarm.triggerTimeAsDateStringSimple(alarm.triggerTime));
        vibrateInput.setChecked(alarm.vibrate);
    }
    
    private void updateAlarmSoundDisplayText(String text) {
        if (StringUtils.isNotBlank(text)) {
            CharSequence truncatedText = TextViewUtils.truncateText(chooseAlarmSoundDisplay, text);
            chooseAlarmSoundDisplay.setText(truncatedText);
        }
    }
    
    private void initModels() {
        alarmTimeModel = createChooseAlarmTimeModel();
        updateAlarmTimeModelWithValuesFromAlarm();
    }
    
    private AlarmTimeModel createChooseAlarmTimeModel() {
        AlarmTimeModel model = new AlarmTimeModel();
        return model;
    }
    
    private void updateAlarmTimeModelWithValuesFromAlarm() {
        long triggerTime = alarm.triggerTime;

        Calendar date = DateTimeUtils.createCalendar(triggerTime);
        
        alarmTimeModel.hour = date.get(Calendar.HOUR_OF_DAY);
        alarmTimeModel.minute = date.get(Calendar.MINUTE);
        
        ClockSettings clockSettings = SettingsManager.instance.getClockSettings();
        alarmTimeModel.militaryTime = clockSettings.isMilitaryTime();
    }
    
    protected void initOnClickListeners() {
        initChooseAlarmTimeAction();
        initChooseAlarmSoundAction();
        initDoneButtonAction();
    }
    
    private void initChooseAlarmTimeAction() {
        ChooseAlarmTimeAction chooseAlarmTimeAction = new ChooseAlarmTimeAction(this, alarmTimeModel);
        chooseAlarmTimeAction.setOnCloseListener(new ChooseAlarmTimeActionOnCloseHandler());
        chooseAlarmTimeDisplay.setOnClickListener(chooseAlarmTimeAction);
    }
    
    private void initChooseAlarmSoundAction() {
        chooseAlarmSoundDisplay.setOnClickListener(new ChooseAlarmSoundHandler());
    }
    
    private void initDoneButtonAction() {
        if (doneButton != null) {
            DoneButtonAction doneButtonAction = new DoneButtonAction();
            doneButton.setOnClickListener(doneButtonAction);
        }
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.edit_alarm_menu, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.doneMenuItem) {
            onDone();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    
    private void onDone() {
        saveAlarmData();
        AlarmManager.instance.addAlarm(alarm, this);
        attachAlarmToActivityResult();
        finish();
    }
    
    private void attachAlarmToActivityResult() {
        Intent data = new Intent();
        data.putExtra(Alarm.ALARM_PARCEL_NAME, alarm);
        setResult(RESULT_ALARM_ADDED, data);
    }
    
    private void saveAlarmData() {
        saveAlarmTimeData();
        saveWidgetAlarmData();
    }
    
    private void saveAlarmTimeData() {
        alarm.triggerTime = alarmTimeModel.getAlarmTimeInMillis();
    }
    
    private void saveWidgetAlarmData() {
        alarm.enabled = enabledInput.isChecked();
        alarm.vibrate = vibrateInput.isChecked();
        alarm.name = nameInput.getText().toString();
    }
    
    private void chooseAlarmSound() {
        RingtoneUtils.promptForRingtoneSelection(this);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (resultCode == RESULT_OK) {
            Uri ringtoneUri = data.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI);
            saveAlarmSoundData(ringtoneUri);
        }
    }
    
    private void saveAlarmSoundData(Uri ringtoneUri) {
        alarm.acceptRingtone(this, ringtoneUri);
        updateAlarmSoundDisplayText(alarm.ringtoneTitle);
    }
    
    private class ChooseAlarmTimeActionOnCloseHandler implements ChooseAlarmTimeAction.OnCloseListener {
        public void onChooseAlarmTimeClose() {
            long triggerTime = alarmTimeModel.getAlarmTimeInMillis();
            String alarmTimeText = Alarm.triggerTimeAsDateStringSimple(triggerTime);
            chooseAlarmTimeDisplay.setText(alarmTimeText);
        }
    }
    
    private class DoneButtonAction implements OnClickListener {
        public void onClick(View v) {
            onDone();
        }
    }
    
    private class ChooseAlarmSoundHandler implements OnClickListener {
        public void onClick(View v) {
            chooseAlarmSound();
        }
    }
    
}
